package com.ews.onlineexchange.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;

import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.UserService;
import org.apache.commons.lang3.StringUtils;
import com.ews.onlineexchange.service.UserHome;

@Named
public class EmailValidator implements Validator {

	@Inject
	UserService userService;
	
	@Inject
	UserHome userHome;
	
	@Override
	public void validate(FacesContext facesContext,
		      UIComponent component, Object value) throws ValidatorException {	
		String newEmail = value.toString();
		User user = userHome.getInstance();
		if (StringUtils.isBlank(userHome.getOldEmail()) 					// 添加 
				|| !newEmail.equals(userHome.getOldEmail())) {				// 修改时，修改了邮箱
			if (userService.isEmailExist(newEmail)) {
				FacesMessage msg =
		            new FacesMessage("邮箱已存在","无效的邮箱地址");
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
		        throw new ValidatorException(msg);
			}
		} 
	}

}
